// 设置原生包名  
package uts.sdk.modules.wencode;  

// 引用系统类  
import android.content.Context  
import android.content.pm.PackageInfo  
import android.content.pm.PackageManager  
import android.content.pm.Signature  
import android.util.Log  
// 引用 uts 基础库相关类  
import io.dcloud.uts.UTSAndroid  
import java.security.MessageDigest  

/**
 * 原生 Kotlin 语言实现封装类  
 */  
object MemoryInfoNative {  

    /**
     * 获取应用签名信息
     * @param packageName 要查询的应用包名
     */  
    fun getSignatureInfo(packageName: String): Map<String, String> {  
		
        val context: Context? = UTSAndroid.getUniActivity()  
        val resultMap = mutableMapOf<String, String>()  

        if (context == null) {
            return resultMap
        }
        
        if (packageName.isEmpty()) {
            return resultMap
        }

        try {  
            // 获取签名信息  
            val packageInfo: PackageInfo? = try {
                context.packageManager.getPackageInfo(  
                    packageName,  
                    PackageManager.GET_SIGNATURES  
                )
            } catch (e: PackageManager.NameNotFoundException) {
                return resultMap
            }

            val signatures: Array<Signature>? = packageInfo?.signatures  
            if (signatures.isNullOrEmpty()) {  
                return resultMap  
            }  

            // 处理第一个签名（通常应用只有一个签名）  
            val signature = signatures[0]  
            val md5 = calculateHash(signature.toByteArray(), "MD5")  
            val sha1 = calculateHash(signature.toByteArray(), "SHA-1")  

            // 存入结果Map  
            resultMap["md5"] = md5 ?: ""  
            resultMap["sha1"] = sha1 ?: ""  

        } catch (e: Exception) {  
            Log.e("SignatureError", "获取签名失败: ${e.message}")  
        }  

        return resultMap  
    }  

    /**
     * 计算哈希值并格式化为标准字符串
     */  
    private fun calculateHash(data: ByteArray, algorithm: String): String? {
        return try {
            val digest = MessageDigest.getInstance(algorithm)
            val hashBytes = digest.digest(data)
    
            // 不带冒号，小写
            val hexString = StringBuilder()
            for (b in hashBytes) {
                val hex = Integer.toHexString(0xff and b.toInt())
                if (hex.length == 1) hexString.append('0')
                hexString.append(hex)
            }
            hexString.toString().lowercase()
        } catch (e: Exception) {
            Log.e("HashError", "$algorithm 计算失败: ${e.message}")
            null
        }
    }
}  